#include "LinkTree.h"
#include <dirent.h>
#include <stdio.h>
#include <string.h>

void ExploreDirectory(const char* path, LTNode* parentNode)
{
    DIR* dir = opendir(path);//打开path路径文件夹
    if(dir == NULL)//空，返回上级递归
       return;
    
    struct dirent* entry ;
    while(entry = readdir(dir))//读取当前文件夹下的目录名
    {
        //忽略".”和".."的文件
        if(strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name,"..") == 0)
            continue;
        struct UniversalType TypeValue;//创建通用数据结构体，关联struct dirent* entry 
        TypeValue.value = entry;
        TypeValue.type = structPoint;
        LTNode* fileNode = CreateTreeNode(TypeValue);
        ConnectBranch(parentNode,fileNode);//以parentNode为父节点，连接入该树

        if(entry->d_type == 4)
        {
            char filePath[100] = {0};
            strcpy(filePath, path);//保存上级文件绝对路径
            strcat(filePath, "/");//给当前文件路径前添加"/"
            strcat(filePath, entry->d_name);//追加当前文件路径，构成当前文件目录的绝对路径
            ExploreDirectory(filePath,fileNode);//递归打开当前文件路径，存在追加新的树节点
        }      
    }
    closedir(dir);//关闭当前打开的文件夹
}

void print(ElementType data)
{

    struct dirent* entry = (struct dirent*)data.value;
    if(entry!= NULL)
    {
        printf(" ");
        printf("|__");
        printf("%s", entry->d_name);
        printf("\n");
    }
}


int main(int argc, char* argv[])
{
    if(argc != 2)
    {
        printf("invalid input numbers\n");
        return 0;
    }

    LTree FileTree;
    InitLTree(&FileTree);

    // FileTree.root->data.value = argv[1];
    ExploreDirectory(argv[1], FileTree.root);
    TravelTree(&FileTree,print);
    return 0;
}
